"""
模板数据模型
"""
from sqlalchemy import Column, Integer, String, SmallInteger, DateTime
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.sql import func

from core.database import Base


class TemplateData(Base):
    """模板数据表"""
    __tablename__ = "template_data"
    
    id = Column(Integer, primary_key=True, index=True, comment="模板数据ID")
    template_id = Column(Integer, nullable=False, index=True, comment="模板表ID（逻辑外键）")
    template_name = Column(String(255), nullable=True, comment="模板表名称（冗余字段）")
    template_version = Column(Integer, nullable=False, comment="模板版本号")
    patient_id = Column(Integer, nullable=False, index=True, comment="患者ID（逻辑外键）")
    patient_name = Column(String(100), nullable=True, comment="患者姓名（冗余字段）")
    doctor_id = Column(Integer, nullable=False, index=True, comment="医生ID（逻辑外键）")
    medical_record_id = Column(Integer, nullable=True, index=True, comment="病历ID（逻辑外键，可选）")
    
    # 表单数据
    form_data = Column(JSONB, nullable=False, comment="模板表单数据（JSON格式）")
    
    # 状态
    status = Column(SmallInteger, nullable=False, default=1, comment="状态 1-启用 0-禁用")
    
    # 时间戳
    created_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        comment="创建时间"
    )
    updated_at = Column(
        DateTime(timezone=True),
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间"
    )
    
    def __repr__(self):
        return f"<TemplateData(id={self.id}, template_id={self.template_id}, patient_id={self.patient_id})>"

